﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using SlamCms.Common;
using SlamCms.Data;
using SlamCmsDemo.Data;
using SlamCmsDemo.Web.Core.Models;

namespace SlamCmsDemo.Web.Core
{
	public static class ContentItemExtensions
	{
		public static ContentList ToContentList(this IEnumerable<ContentItem> contentItems, string title, Func<ContentItem, bool> isFeatured = null)
		{
			if (contentItems == null)
				throw new ArgumentNullException("contentItems");

			return new ContentList()
			{
				Title = title,
				Items = contentItems.ToContentList(isFeatured).ToList()
			};
		}

		public static IEnumerable<ContentListItem> ToContentList(this IEnumerable<ContentItem> contentItems, Func<ContentItem, bool> isFeatured = null)
		{
			if (contentItems == null)
				throw new ArgumentNullException("contentItems");

			return contentItems.Select(x => x.ToContentListItem(isFeatured != null && isFeatured(x)));
		}

		public static ContentListItem ToContentListItem(this ContentItem contentItem, bool featured = false)
		{
			if (contentItem == null)
				throw new ArgumentNullException("contentItem");

			var urlHelper = DependencyResolver.Current.GetService<UrlHelper>();

			var contentListItem = new ContentListItem()
			{
				ContentItem = contentItem,
				Title = contentItem.ReferenceTitle,
				Url = urlHelper.ContentItemDetails(contentItem),
				Featured = featured
			};

			// Article
			contentListItem.CustomizeIf<Article>(x =>
			{
				contentListItem.Title = x.Title;
				contentListItem.Description = x.Description.TruncateWithEllipsis(250);
				contentListItem.Icon = "Article";
			});

			// Download
			contentListItem.CustomizeIf<Download>(x =>
			{
				contentListItem.Title = x.Title;
				contentListItem.Description = x.Description.TruncateWithEllipsis(250);
				contentListItem.Icon = "Download";
			});

			// Event
			contentListItem.CustomizeIf<Event>(x =>
			{
				contentListItem.Title = x.Title;
				contentListItem.Description = x.Description.TruncateWithEllipsis(250);
				contentListItem.Icon = "Event";
			});

			// Faq
			contentListItem.CustomizeIf<Faq>(x =>
			{
				contentListItem.Title = x.Question;
				contentListItem.Description = x.Answer.TruncateWithEllipsis(250);
				contentListItem.Icon = "Faq";
			});

			return contentListItem;
		}

		private static ContentListItem CustomizeIf<T>(this ContentListItem contentListItem, Action<T> customizationFunction) where T : ContentItem
		{
			if (contentListItem == null)
				throw new ArgumentNullException("contentListItem");

			if (customizationFunction == null)
				throw new ArgumentNullException("customizationFunction");

			var converted = contentListItem.ContentItem as T;
			if (converted == null)
				return contentListItem;

			customizationFunction(converted);

			return contentListItem;
		}
	}
}